#include <stdio.h>
#include <unistd.h>
int affected(FILE *fp, FILE *fpv, int n);
int main(int argc, char *argv[])
{
  FILE *fp,*fpv,*fpt;
  int stu;
  char c,d;
  int i,SZ=56475;
  long le;
  char *tmpfile="/home/rong/virtmp";
  if(argc!=2) {printf("Incorrect call, usage: killvir file\n");}
  fp=fopen(argv[1],"r");
  if(!fp){printf("cannot open file %s \n",argv[1]);return 1;};
  if(fseek(fp,SZ,SEEK_SET)) {fclose(fp);return 1;}
  c=fgetc(fp);
  d=fgetc(fp);
  if(c=='M' && d=='Z'){
    // fseek(fp,0,SEEK_SET);
    fpv=fopen("/home/rong/logovir.exe","r");
    if(!fpv){
      printf("cannot open virus sample file /home/rong/logovir.exe \n");
      fclose(fp);
      return 1;
    }
   
    if(affected(fp,fpv,SZ)){
      //truncate(tmpfile,0);
       fpt=fopen(tmpfile,"w+");
       if(!fpt){
          printf("can not open file %s for write\n",tmpfile);
          return 1;
       }
    fclose(fpv);
    
    //c=fgetc(fp);
    //printf("%c\n",c);
    fseek(fp,0,SEEK_END);
    le=ftell(fp);
    le=le-SZ;
    // printf("%d\n",le);
    fseek(fp,SZ,SEEK_SET); 
    for (i=0;i<le;i++) {c=fgetc(fp);fputc(c,fpt);}
    fclose(fp);
    //printf("ftell: %d\n",ftell(fpt));
    //truncate(argv[1],0);
    fp=fopen(argv[1],"w");
    fseek(fpt,0,SEEK_SET);
    //printf("ftell: %d\n",ftell(fpt));
    for (i=0;i<le;i++) {c=fgetc(fpt);fputc(c,fp);}
    //while ((c=fgetc(fpt))!=EOF) fputc(c,fp); 
    //printf("ftell: %d\n",ftell(fpt));
    fseek(fpt,0,SEEK_END);
    //printf("ftell: %d\n",ftell(fpt));
    printf("Repair %s successfully\n",argv[1]);
    fclose(fp); 
    fclose(fpt);
    return 0;
    }
  }
  fclose(fp);
  return 1;
}


int affected(FILE *fp,FILE *fpv,int n){
   int i;
   char c1,c2;
   fseek(fp,0,SEEK_SET);
   fseek(fpv,0,SEEK_SET);
   for(i=0;i<n;i++) {
     c1=fgetc(fp);
     c2=fgetc(fpv);
     //  printf("c1 %c<===>c2 %c\n",c1,c2);
     if(c1!=c2) return 0;
   }
   return 1;
}
